package cn.lopr.im.android.mvp.view.activities;

import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.telephony.SmsMessage;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.lopr.im.android.bean.User;
import cn.lopr.im.android.common.app.Activity;
import cn.lopr.im.android.databinding.ActivityRegisterBinding;
import cn.lopr.im.android.mvp.contact.IRegisterContact;
import cn.lopr.im.android.mvp.presenter.RegisterPresenterImpl;

public class RegisterActivity extends Activity implements IRegisterContact.IRegisterView {

    private final String TAG = "RegisterActivity";
    ActivityRegisterBinding binding;
    private RegisterPresenterImpl registerPresenterImpl;
    private SmsObserver smsObserver;

    final private int REQUEST_CODE_ASK_PERMISSIONS = 123;

    @Override
    protected View getContentLayoutId() {
        binding = ActivityRegisterBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initWidget() {
        super.initWidget();
    }

    @Override
    protected void initData() {
        super.initData();
        this.registerPresenterImpl = new RegisterPresenterImpl(this, this);

        this.binding.btnSubmit.setOnClickListener(e -> registerPresenterImpl.reg());
        this.binding.txtGoLogin.setOnClickListener(e -> RegisterActivity.this.finish());

        this.binding.btnCode.setOnClickListener(e -> registerPresenterImpl.getCode());


        this.smsObserver = new SmsObserver(new Handler());
        getContentResolver().registerContentObserver(Uri.parse("content://sms"), true, this.smsObserver);

    }


    @Override
    public void regSuccess(User result) {
        Intent intent = new Intent(RegisterActivity.this, RegisterBeforeActivity.class);
        intent.putExtra("reg", result);
        getApplicationContext().startActivity(intent);
    }

    @Override
    public void regFailure(String message) {

    }

    @Override
    public void showMessage(String message) {
        Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_LONG).show();
    }

    private class SmsObserver extends ContentObserver {

        public SmsObserver(Handler handler) {
            super(handler);
        }

        /**
         * Uri.parse("content://sms/inbox")表示对收到的短信的一个监听的uri.
         */
        @Override
        public void onChange(boolean selfChange) {
            Log.i(TAG, "onChange: ");
            StringBuilder sb = new StringBuilder();
            Cursor cursor = getContentResolver().query(
                    Uri.parse("content://sms/inbox"), null, null, null, null);
            //这里不要使用while循环.我们只需要获取当前发送过来的短信数据就可以了.
            cursor.moveToNext();
            sb.append("body=").append(cursor.getString(cursor.getColumnIndex("body")));  //获取短信内容的实体数据.
            Pattern pattern = Pattern.compile("[^0-9]");  //正则表达式.
            Matcher matcher = pattern.matcher(sb.toString());
            String code = matcher.replaceAll("");
            code = code.substring(0, code.length() - 1);
            binding.etCode.setText(code);  //将输入验证码的控件内容进行改变.
            cursor.close();  //关闭游标指针.
            super.onChange(selfChange);
        }
    }

    public class SMSReceiver extends BroadcastReceiver {

        private static final String TAG = "SMSReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            //进行获取短信的操作
            getMsg(context, intent);
        }
    }

    private void getMsg(Context context, Intent intent) {
        Object[] pdus = (Object[]) intent.getExtras().get("pdus");
        assert pdus != null;
        for (Object pdu : pdus) {
            //封装短信参数的对象
            SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdu);
            String number = sms.getOriginatingAddress();
            String body = sms.getMessageBody();
            //写自己的处理逻辑
            //获取短信验证码
            getCode(context, body);
        }
    }

    private void getCode(Context context, String body) {
        //获取剪贴板管理器：
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);

        Pattern pattern1 = Pattern.compile("(\\d{6})");//提取六位数字
        Matcher matcher1 = pattern1.matcher(body);//进行匹配

        Pattern pattern2 = Pattern.compile("(\\d{4})");//提取四位数字
        Matcher matcher2 = pattern2.matcher(body);//进行匹配

        if (matcher1.find()) {//匹配成功
            String code = matcher1.group(0);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", code);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            Toast.makeText(context, "验证码复制成功", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "onReceive: " + code);
        } else if (matcher2.find()) {
            String code = matcher2.group(0);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", code);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            Toast.makeText(context, "验证码复制成功", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "onReceive: " + code);
        } else {
            Toast.makeText(context, "未检测到验证码", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "onReceive: " + "未检测到验证码");
        }
    }


    @Override
    public String getPhone() {
        String phone = this.binding.etPhone.getText().toString();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(RegisterActivity.this, "请输入手机号", Toast.LENGTH_LONG).show();

        }
        return phone;
    }

    @Override
    public String getPassword() {
        return this.binding.etPassword.getText().toString();
    }

    @Override
    public String getName() {
        return this.binding.etName.getText().toString();
    }

    @Override
    public void finish() {
        super.finish();
        getContentResolver().unregisterContentObserver(this.smsObserver);
    }
}